(function(){
    if(!window.jQuery)return;
    var forExtend;
    forExtend = {
        shiftFun: function(menu, contents, shifter){
            if(typeof(contents) == "function"){
                contents = contents($(shifter).data("shifter"));
            }
            if(contents === false)return;
            $(menu).find("[data-shifter].active").removeClass("active");
            $(menu).find("[data-shifter=" + shifter + "]").addClass("active");
            if(contents){
                $(contents).removeClass("active");
                $(contents).filter("[data-shift=" + shifter + "]").addClass("active");
            }
        }
    };
    $.fn.extend({
        bindShifter: function(contents, method, cancel){
            var shiftFun = forExtend.shiftFun, self = this;
            if(!cancel)$(self).on((method || "click") + ".bindShifter", "[data-shifter]", function(e){
                if($(this).hasClass("active"))return;
                shiftFun(self, contents, $(this).data("shifter"));
            });
            else{
                var t, _this;
                $(self).on((method || "click") + ".bindShifter", "[data-shifter]", function(e){
                    if($(_this = this).hasClass("active"))return;
                    t = setTimeout(function(){shiftFun(self, contents, $(_this).data("shifter"));clearTimeout(t);}, cancel.after);
                });
                $(self).on(cancel.method + ".bindShifter", "[data-shifter]", function(e){
                    clearTimeout(t);
                });
            }
            return function(to){shiftFun(self, contents, to);};
        }
    });
})();

//获取天气
(function getWeather(){
    var city = localStorage.getItem("gate-WeatherCity") || "";
    if(!window.WCB)window.WCB = function(res){
        var chilren, wt;
        for(var i in res.w){
            $("#city").text((city = i) + "[切换]");
            $.each(res.w[i], function(j, item){
                chilren = $("#weather" + j).children();
                wt = item.s1 || item.s2;
                chilren[0].innerHTML = (j ? "明天 " : "今天 ") + (item.s1 ? item.s1 + "~" + item.s2 : item.s2);
                chilren[1].innerHTML = (item.t1 ? item.t2 + "℃ ~" + item.t1 : item.t2) + "℃";
                chilren[0].className = wt.indexOf("雷") >= 0 ? "icon-flash" :
                    wt.indexOf("雨") >= 0 ? "icon-umbrella" :
                    wt.indexOf("阴") >= 0 || wt.indexOf("云") >= 0 ? "icon-cloud" :
                    Math.abs(new Date().getHours() - 12) > 6 ? chilren[0].className = "icon-moon" : "icon-sun";
            });
            break;
        }
        localStorage.setItem("gate-WeatherCity", city);
    };
    $.ajax({
        type: "get",
        url: "http://php.weather.sina.com.cn/iframe/index/w_cl.php?code=js&charset=utf-8&day=1&cbf=WCB&city="+encodeURI(city),
        dataType: "script"
    });
})();

//获取新闻
(function getNews(){
    //TODO 储存新闻（今日头条现在不会推送重复新闻，要在没有新闻的时候取localstorage）
    var newsList = JSON.parse(localStorage.getItem("gate-newsList") || '[]'), newsHTML, j;
    $.ajax({
        url: "http://toutiao.com/api/article/recent/",
        data: {category: "news_hot", count: 8},
        dataType: "jsonp",
        success: function(res, msg){
            if(msg !== "success")return false;
            newsList = newsList.concat(res.data).slice(-8);
            newsHTML = "";
            $.each(newsList, function(i, news){
                newsHTML += '<p><a href="http://toutiao.com/' + news.source_url + '">' + news.title + '</a></p>';
//              ["title", "keywords", "has_image", "image_url", "image_list", "source", "source_url", "datetime"]
            });
            $("#newsContent").html(newsHTML);
            localStorage.setItem("gate-newsList", JSON.stringify(newsList));
        }
    });
})();

(function(window, undefined){
var userStats;
//各种切换
var bannerShifter = $(".search-banners").bindShifter(".banner-options", "click");
$(".search-banner").on("click", function(e){
    $("#search").focus();
});
function shifterByClickThenMouseenter($sel, contentSel){
    $sel.each(function(i, shifter){
        var $shifter = $(shifter);
        $shifter.bindShifter(function(to){
            $shifter.off(".bindShifter").bindShifter(contentSel, "mouseover");
            $shifter.on("mouseleave", function(e){
                $shifter.off(".bindShifter");
                shifterByClickThenMouseenter($shifter, contentSel);
            });
            return contentSel;
        });
    });
}
shifterByClickThenMouseenter($(".banner-options"));
shifterByClickThenMouseenter($(".gate-category"), ".gate-links");

//搜索联想
var sst, wordJustNow, ssText, wordOrigin = false;
function searchSuggestion(){
    if(!$("#search").val() || wordJustNow === $("#search").val())
        return $(".s-suggestion").hide();
    $(".s-suggestion").show();
    $.ajax({
        url: "http://suggestion.baidu.com/su",
        data: {wd: wordJustNow = $("#search").val()},
        dataType: "jsonp",
        jsonp: "cb",
        success: function(res, msg){
            if(msg !== "success")return false;
            ssText = "";
            $.each(res.s, function(i, t){
                ssText += '<p>' + t + '</p>';
            });
            $(".s-suggestion").html(ssText);
        }
    });
}
$("#search").on("input", function(e){
    clearTimeout(sst);
    sst = false;
    wordOrigin = $("#search").val();
    sst = setTimeout(searchSuggestion, 300);
}).on("keydown", function(e){
    if(e.keyCode == 40){
        //如果是下键
        e.preventDefault();
        $(".s-suggestion>p.active").length
        ? $(".s-suggestion>p.active").removeClass("active").next().addClass("active")
        : $(".s-suggestion>p:first-child").addClass("active");
    } else if(e.keyCode == 38){
        //如果是上键
        e.preventDefault();
        $(".s-suggestion>p.active").length
        ? $(".s-suggestion>p.active").removeClass("active").prev().addClass("active")
        : $(".s-suggestion>p:last-child").addClass("active");
    }
    var activeWord = $(".s-suggestion>p.active").text();
    if(activeWord && $("#search").val() != activeWord)$("#search").val(activeWord);
});
$(document).on("mousedown focus", function(e){
    if($(e.target).closest("#searchForm").length)return;
    clearTimeout(sst);
    $(".s-suggestion").hide();
});
$(".s-suggestion").on("mouseenter", "p", function(e){
    $(".s-suggestion>p.active").removeClass("active");
    $(this).addClass("active");
    $("#search").val($(".s-suggestion>p.active").text());
}).on("mouseleave", function(e){
    $(".s-suggestion>p.active").removeClass("active");
    $("#search").val(wordOrigin);
}).on("click", "p", function(e){
    $("#search").val($(this).text());
    $(".s-suggestion").empty().hide();
    $("#searchForm").submit();
});

//hover focus搜索
$("#search").on("mouseenter", function(){if(this != document.activeElement)$(this).focus().select();})
.on("click", searchSuggestion);

//搜索提交
var googleTransition = {page: "", image: "isch", video: "vid"},
    baiduTransition = {
        page: {action: "http://www.baidu.com/s", input: "word"},
        image: {action: "http://image.baidu.com/search/index", input: "word", hidden: ["tn", "baiduimage"]},
        video: {action: "http://v.baidu.com/v", input: "word", hidden: ["ie", "utf-8"]},
        music: {action: "http://music.baidu.com/search", input: "key"},
        zhidao: {action: "http://zhidao.baidu.com/search", input: "word"},
        baike: {action: "http://baike.baidu.com/search/word", input: "word"},
        map: {action: "http://map.baidu.com/m", input: "word"},
        dict: {action: "http://dict.baidu.com/s", input: "word"}
    };
$("#searchForm").on("submit", function(e){
    var sText = $("#search").val(),
        site = $(".banner-options.active").data("shift"),
        type = $(".banner-options.active [data-shifter].active").data("shifter"),
        name;
//  if(!sText)return e.preventDefault(), false;
    switch(site){
        case "google":
            $("#searchForm").attr("action", "https://www.google.com/search");
            $("#search").attr("name", "q");
            $("#searchHidden").attr("name", "tbm");
            if(type == "map"){
                e.preventDefault();
                var evt = document.createEvent("MouseEvents");evt.initEvent("click", false, false);
                $('<a class="hide" href="https://www.google.com/maps/search/' + encodeURI(sText) + '"></a>')[0].dispatchEvent(evt);
            } else $("#searchHidden").val(googleTransition[type] || "");
            break;
        case "baidu":
            $("#searchForm").attr("action", baiduTransition[type].action);
            $("#search").attr("name", baiduTransition[type].input);
            if(baiduTransition[type].hidden)
                $("#searchHidden").attr("name", baiduTransition[type].hidden[0]).val(baiduTransition[type].hidden[1]);
            break;
        case "bing":
            $("#searchForm").attr("action", "http://cn.bing.com/" + (type == "page" ? "" : type + "/") + "search");
            $("#search").attr("name", "q");
            break;
        case "wiki":
            $("#searchForm").attr("action", "http://zh.wikipedia.org/w/");
            $("#search").attr("name", "search");
            break;
        case "taobao":
            $("#searchForm").attr("action", "http://s.taobao.com/search");
            $("#search").attr("name", "q");
            break;
        default:
            return false;break;
    }
    $("#search").select();
    searchSuggestion();
    clearTimeout(sst);
    sst = false;
    $(".s-suggestion").hide();
//  if(!userStats.search[site])userStats.search[site] = {n: 0};
//  userStats.search[site].n++;
//  userStats.search[site][type];
//  localStorage.setItem("gate-search", JSON.stringify(userStats));
});

function logoGateLinks(){
    var styleText = '.gate-links li a:before{display: inline-block;background-repeat: no-repeat;background-size: contain;text-shadow: -1px 1px 2px rgba(0,0,0,.3)',
        i;
    for(i = 2; i < 6; i++){styleText += ',' + -i + 'px ' + i + "px 2px rgba(0,0,0,.3)"}
    styleText += ';}';
    $(".gate-links li a").each(function(){
        var $this = $(this);
        var url = $this.attr("href");
        url = url ? new URL($this.attr("href")) : '';
        var text = $this.text().replace(/[\s\.\#\[\]\~\`\!\@\$\%\^\&\*\(\)\{\}\+\=\;\:\<\>\,\/\?\'\"]/g, "");
        var num = "";
        $.each(text.split(""), function(i,s){num += s.charCodeAt(0);});
        var color = num % 360;
        text && $this.attr("logo", text[0].toUpperCase()).addClass("gl-bf-" + text);
        styleText += ".gl-bf-" + text + ':before{content: attr(logo);color: hsl(' + color + ',90%,95%);background-color: hsl(' + color + ',55%,55%);}';
        if(url && url.host){
            var img = new Image;
            img.onload = function(){
                $(".gl-bf-" + text).removeAttr("logo");
                $("#logoStyle").append(".gl-bf-" + text
                    + ':before{content: "\\B";background-color: transparent;background-image: url('
                    + img.src + ')}');
            };
            img.src = url.origin + "/favicon.ico";
        }
    });
    $(document.head).append('<style id="logoStyle">' + styleText + "</style>");
}

$(".gate-category>.icon-setting").click(function(e){
    $(".gate-links").toggleClass("gate-editing");
});

//debug
$(".gate-links ul").on("dragstart", "li", function(e){
    //开始拖动的动作
});
$(".gate-links ul").on("dragenter", "li", function(e){
    //进入其它元素位置的动作，用于排序
});
$(".gate-links ul").on("dragenter", function(e){
    //对允许拖动的容器设置 dragover 的 e.preventDefault 才能允许拖动（即触发ondrop事件）
    e.preventDefault();
});
$(".gate-links ul").on("drop", function(e){
    console.log(e);
});

(function init(){
    bannerShifter("google");
    userStats = {search: {}, cloudbox: {}, email: {}, gate: {}};
    $(logoGateLinks);
})();
})(window);



